//
//  CZUserAccountViewModel.swift
//  SinaWeibo_Swift
//
//  Created by TianZhen on 16/4/11.
//  Copyright © 2016年 TianZhen. All rights reserved.
//

import UIKit

class WBUserAccountViewModel: NSObject {
    // 单例
    static let sharedInstance = WBUserAccountViewModel()
    
    private override init() {
        super.init()
        
        // 单例的init只执行一次
        // 加载账号
        userAccount = loadUserAccount()
    }
    
    /// 账号模型，只要那到单例就可以访问到,全局通用.
    var userAccount: WBUserAccount?
    
    /// 用户是否登录
    var userLogin: Bool {
        get {
            return userAccount != nil
        }
    }
    
    /// 获取accessToken
    // 1.定闭包类型,通过函数的参数传递
    func loadAccessToken(code: String, loadAccessTokenCallback: (error: NSError?) -> ()) {
        // 1.urlString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 2.参数，字典
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": grant_type,
            "code": code,
            "redirect_uri": redirect_uri
        ]
        WBNetTool.sharedInstance.POST(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
            // as: 表示类型转换
            // as?: 有可能转成功,有可能转失败
            // as!: 一定能转成成功,如果转换失败,直接挂了
            let result = responseObject as? [String: AnyObject]
            
            if let dict = result {
                // 字典转模型,并且赋值给属性
                self.userAccount = WBUserAccount(dict: dict)
                self.saveUserAccount()
                // 2.通知控制器账号加载完成了,调用闭包
                loadAccessTokenCallback(error: nil)
            }
            }) { (task, error) -> Void in
                // 2.通知控制器账号加载出错了,调用闭包
                loadAccessTokenCallback(error: error)
        }
    }
    
    /// 保存账号模型
    private func saveUserAccount() {
        //        HMPrint("accountPath: \(accountPath)")
        
        if let userAccount = self.userAccount {
            // 归档,NSKeyedArchiver.archiveRootObject才是归档对象到accountPath
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
        }
    }
    
    /// 从沙盒里面解档UserAccount对象
    func loadUserAccount() -> WBUserAccount? {
        
        // 解档账号,有可能有,有可能没有
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? WBUserAccount
        
        // 可选绑定, 判断账号是否有值,账号有值,判断是否过期
        // 测试过期时间,
        //        userAccount?.expiresDate = NSDate(timeIntervalSinceNow: -100)
        if let account = userAccount where account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            //            HMPrint("没有过期: \(account)")
            return account
        }
        
        return nil
    }
    
    // MARK: - 获取用户信息
    func loadUserInfo(loadUserInfoCallback: (error: NSError?) -> ()) {
        guard let access_token = userAccount?.access_token else {
            let error = WBNetToolError.emptyToken.error()
            loadUserInfoCallback(error: error)
            return
        }
        guard let uid = userAccount?.uid else {
            let error = WBNetToolError.emptyUid.error()
            loadUserInfoCallback(error: error)
            return
        }
        // url
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 参数
        let parameters = [
            "access_token" : access_token,
            "uid": uid
        ]
        // 发送请求
        WBNetTool.sharedInstance.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
            if let dict = responseObject as? [String: AnyObject] {
                // 将获取到得数据赋值给当前账号
                self.userAccount?.screen_name = dict["screen_name"] as? String
                self.userAccount?.avatar_large = dict["avatar_large"] as? String
                self.saveUserAccount()
                
                loadUserInfoCallback(error: nil)
            }
            }) { (task, error) -> Void in
                loadUserInfoCallback(error: error)
        }
    }
}
